package com.weayer.remote;

import com.weayer.constant.AmapConfigConstants;
import com.weayer.constant.CommonStatusEnum;
import com.weayer.dto.ResponseResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @description: 调用行政区划服务Client
 * @author: Weayer
 **/
@Service
public class MapDistrictClient {
    @Value("${amap.key}")
    private String amapKey;
    @Autowired
    private RestTemplate restTemplate;

    public String district(String keywords){
        // 1. 组装url: https://restapi.amap.com/v3/config/district?keywords=北京&subdistrict=2&key=<用户的key>
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstants.DISTRICT_URL_PREFIX);
        urlBuilder.append("?");
        urlBuilder.append("keywords=" + keywords);
        urlBuilder.append("&");
        urlBuilder.append("subdistrict=2");
        urlBuilder.append("&");
        urlBuilder.append("key=" + amapKey);
        urlBuilder.append("&");
        // 2. 调用高德地图api
        ResponseEntity<String> districtEntity = restTemplate.getForEntity(urlBuilder.toString(), String.class);

        // 3. 解析接口
        return parseDistrictEntity(districtEntity.getBody());
    }
    public String parseDistrictEntity(String districtString){
        JSONObject result = JSONObject.fromObject(districtString);
        if(result.has(AmapConfigConstants.STATUS)){
            int status = result.getInt(AmapConfigConstants.STATUS);
            if(status == 1){
                if(result.has(AmapConfigConstants.DISTRICT)){
                    JSONArray districtsArray = result.getJSONArray(AmapConfigConstants.DISTRICT);
                    JSONObject routeObject = result.getJSONObject(AmapConfigConstants.ROUTE);
                    JSONArray pathsArray = routeObject.getJSONArray(AmapConfigConstants.PATHS);
                    JSONObject pathObject = pathsArray.getJSONObject(0);

                    if(pathObject.has(AmapConfigConstants.DISTANCE)){
                        int distance = pathObject.getInt(AmapConfigConstants.DISTANCE);

                    }
                    if(pathObject.has(AmapConfigConstants.DURATION)){
                        int duration = pathObject.getInt(AmapConfigConstants.DURATION);
                    }
                }
            }else{
                return null;
            }
        }
        return "";
    }
}
